#include "SceneManager.hpp"
#include "Camera.hpp"
#include "Device.hpp"
#include "Engine/Renderer/Text.hpp"
#include "Engine/Renderer/VAO.hpp"

namespace red {
	SceneManager::SceneManager() : mDevice(0), mActiveCamera(0), mAmbientLight(Color(0.4f,0.4f,0.4f)){
	}

	SceneManager::~SceneManager(){
		if(mActiveCamera){
			delete mActiveCamera;
			mActiveCamera = 0;
		}

		if(!mTextList.empty())
			for(u32 i = 0; i < mTextList.size(); ++i)
				delete mTextList[i];

		mTextList.clear();
		mVAOList.clear();
	}

	void SceneManager::Init(Device* pDevice){
		mDevice = pDevice;
	}

	Camera* SceneManager::AddCamera(const Vector3F &pPosition, const std::string &pName, f32 pSpeed, f32 pRPM){
		if(!mDevice)
			return NULL;

		if(mActiveCamera)
			delete mActiveCamera;

		mActiveCamera = new Camera(pPosition);
		mActiveCamera->Init(mDevice);
		mActiveCamera->SetName(pName);
		mActiveCamera->SetSpeed(pSpeed);
		mActiveCamera->SetRPM(pRPM);

		return mActiveCamera;
	}

	void SceneManager::HandleCameraInputs(){
		mActiveCamera->HandleInputs();
		if(mActiveCamera->Updated()){
			s1.Bind();
			s1.SendMatrix4("ViewProjMatrix", mDevice->GetRenderer().Get3DViewProjMatrix());
			mActiveCamera->SetUpdated(false);
		}
	}

	Text* SceneManager::AddText(const std::string &pText, const Vector2I &pPosition, const Color &pColor, s16 pSize, bool pBold, bool pItalic){
		mTextList.push_back(new Text(pPosition, pText, pColor, sf::Font::GetDefaultFont(), pSize, pBold, pItalic));

		return mTextList[mTextList.size() - 1];
	}

	void SceneManager::AddVAO(VAO* pVao){
		mVAOList.push_back(pVao);
	}

	void SceneManager::RenderAll(){
		// Render VAOs
		s1.Bind();
		for(u32 i = 0; i < mVAOList.size(); ++i)
			mDevice->GetRenderer().DrawVAO(mVAOList[i]);
			//if(mVAOList[i]->IsEnabled())

		s1.UnBind();


		// Render Texts
		mDevice->GetWindow().GetWindow().myRenderer.myTextureIsValid = false;
		glDisable(GL_DEPTH_TEST);
		glDisable(GL_CULL_FACE);

		for(u32 i = 0; i < mTextList.size(); ++i)
			if(mTextList[i]->IsEnabled())
				mTextList[i]->Draw(mDevice->GetWindow());
		
		glEnable(GL_CULL_FACE);
		glEnable(GL_DEPTH_TEST);

	}
}